#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.db import models
from researchSNS.SNS.models import User
from researchSNS.QA.models import Question,QATag,Answer
from researchSNS.Group.models import Group
from django.http import Http404, HttpResponse,HttpResponseRedirect
import datetime
from django.shortcuts import render_to_response
from django.template import Context,Template
from django.template.loader import get_template
import markdown
import codecs
from django.db.models import Q

#Author  shengdakui
def add_detail(request):
    return render_to_response('add_detail.html')

def add_question(request):
   
    title_error = ''
    description_error = ''
    tag_error = ''
    Title = ''
    Description = ''
    Tag = ''
    group = ''
    user_id = request.session.get('user_id')
    if not user_id:
        return render_to_response('add_question.html', {'user':''})
    user = User.objects.get(id = user_id)
    if 'title' not in request.GET:
        if 'description' not in request.GET:
            questions = user.questions.all()
            return render_to_response('add_question.html', {'questions':questions,'user':user})
    
    if request.method == 'GET':
        Title = request.GET['title']
        if len(request.GET.get('title', '')) < 5:
            title_error = 'title must be at least 5 words'
        Description = request.GET['description']
        if len(request.GET.get('description','')) < 10:
            description_error = 'description must be at least 10 words'
        if 'tag' in request.GET:
            Tag = request.GET['tag']    
            word_list = Tag.strip().split(' ')
            if len(word_list)>= 6:
                tag_error = '5 tags at most for a question'
        if title_error == '' and description_error == '' and tag_error == '':
            Description = markdown.markdown(Description)
            new_question = Question(title = Title,description = Description,questioner = user)
            new_question.save()
            if 'tag' in request.GET:
                Tag = request.GET['tag']    
                word_list = Tag.strip().split(' ')
            for word in word_list:
                if word == '':
                    continue
                if not QATag.objects.all().filter(name=word):
                    tag = QATag( name=word)
                    tag.save()
                    tag.user.add(user)
                    new_question.tags.add(tag)                    
                else:
                    tag = QATag.objects.all().get(name=word)
                    tag.count = tag.count + 1
                    tag.save()
                    new_question.tags.add(tag)
            if 'group' in request.GET:
                group = request.GET['group']    
                word_list = group.strip().split(' ')
            for word in word_list:
                if word == '':
                    continue
                if Group.objects.all().filter(name=word): 
                    group = Group.objects.all().get(name=word)
                    print word
                    print group.name
                    new_question.groups.add(group)
            return HttpResponseRedirect('/qa/questions/')
        else:
            if 'tag' in request.GET and request.GET['tag']:
                Tag = request.GET['tag']
            if 'group' in request.GET and request.GET['group']:
                group = request.GET['group']
            return render_to_response('add_question.html',{'tag_error':tag_error,'title_error':title_error,'description_error':description_error,'title':Title,'description':Description,'tag':Tag,'user':user,'group':group})

def add_answer(request,offset):
    offset = int(offset)
    current = Question.objects.all()[offset-1]

    answer_container = current.answer_set.all()
    if not answer_container:
   	return render_to_response('add_answer.html',{'current':current,'answer_container':answer_container})

def add_answer_form(request, str_offset):
    offset = int(str_offset)
    current = Question.objects.get(id = offset)
    error = ''  
    # if the question has been answered, add answer operation is not permitted  
    user_have_answered = False
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    user = User.objects.get(id = user_id)
    for answer in current.answer_set.all():
        if answer.answerer.name == user.name:
            user_have_answered = True 
    if 'description' in request.GET and request.GET['description']:           
        Description = request.GET['description']    
    answers = current.answer_set.all()
    answer_num = answers.count()
    if user_have_answered:
        error = 'An question can be answered only once by a user'
    elif len(Description)<10:
        print len(Description)
        error = '10 words at least for the answer'
    else:
        Description = markdown.markdown(Description)
        new_answer = Answer(question = current,description = Description,answerer = user)
        current.answered_count = current.answered_count + 1;
        current.save()
        new_answer.save()
        return HttpResponseRedirect('/qa/questions/' + str_offset)    
    return render_to_response("showQuestion.html", {"question":current,'user':user,"answer_list":answers,"answer_num":answer_num,'error':error,'Description':Description})

#add by sdk
#used to help to make list ‘分页’ function 
def make_list(CurrentNum,PageTotalNum):
    i = CurrentNum
    PageList = []
    if PageTotalNum == 1:
        PageList = []
    elif PageTotalNum <= 10:
        i = 1
        while i <= PageTotalNum:
            PageList.append(i)
            i = i + 1
    elif CurrentNum <= 5:
        i = 1
        while i <= 10:
            PageList.append(i)
            i = i + 1
    elif CurrentNum >= PageTotalNum - 5:
        i = PageTotalNum - 9
        while i <= PageTotalNum:
            PageList.append(i)
            i = i + 1
    else:
        i = CurrentNum - 5
        while i < CurrentNum + 5:
            PageList.append(i)
            i = i + 1
    return PageList

# Author: liuguojun
def hello(request):
    return HttpResponse("Hello world")

def question(request):
    RepresentNum = 10
    QuestionNum = len(Question.objects.all())
    PageTotalNum = QuestionNum/RepresentNum
    if PageTotalNum * RepresentNum < QuestionNum:
        PageTotalNum += 1
    q = Question.objects.order_by('-question_datetime')[:RepresentNum]
    tag_list = QATag.objects.order_by('-count')[0:10]
    CurrentNum = 1
    i = CurrentNum
    PageList = []
    if PageTotalNum == 1:
        PageList = []
    else:
        while i < CurrentNum + 10:
            PageList.append(i)
            if i >= PageTotalNum:
                break
            i = i + 1
    return render_to_response("zhima.html", {"question_list":q, "head":"All Questions", "tag_list":tag_list,'PageTotalNum':PageTotalNum,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList})

def showQuestion(request, offset):
    qid = int(offset)
    try:
        question = Question.objects.get(id=qid)
    except:
        return HttpResponseRedirect('/qa/')
    question.view_count += 1
    question.save()
    answers = question.answer_set.all()
    answer_num = answers.count()
    user_id = request.session.get('user_id')
    user = ''
    if  user_id:
        user = User.objects.get(id = user_id)
    return render_to_response("showQuestion.html", {"question":question,'user':user,"answer_list":answers,"answer_num":answer_num})	


# Author: shengdakui   Content about vote page
def vote_question_up(request,offset):
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    user = User.objects.get(id = user_id)
    qid = int(offset)
    current = Question.objects.get(id = qid)
    if user not in current.pro_record.all():
        if user not in current.against_record.all():
            current.vote_count += 1
            current.save()
            current.pro_record.add(user)
    else:
        current.vote_count -= 1
        current.save()
        current.pro_record.remove(user)
    return HttpResponseRedirect('/qa/questions/' + offset)

def vote_question_down(request,offset):
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    user = User.objects.get(id = user_id)
    qid = int(offset)
    current = Question.objects.get(id = qid)
    if user not in current.against_record.all():
        if user not in current.pro_record.all():
            current.vote_count -= 1
            current.save()
            current.against_record.add(user)
    else: 
        current.vote_count += 1
        current.save()
        current.against_record.remove(user)
    return HttpResponseRedirect('/qa/questions/' + offset)

def vote_answer_up(request,offset):
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    user = User.objects.get(id = user_id)
    qid = int(offset)
    current = Answer.objects.get(id = qid)
    if user not in current.pro_record.all():
        if user not in current.against_record.all():
            current.vote_count += 1
            current.save()
            current.pro_record.add(user)
    else:
        current.vote_count -= 1
        current.save()
        current.pro_record.remove(user)
    return HttpResponseRedirect('/qa/questions/' + offset)

def vote_answer_down(request,offset):
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    user = User.objects.get(id = user_id)
    qid = int(offset)
    current = Answer.objects.get(id = qid)
    if user not in current.against_record.all():
        if user not in current.pro_record.all():
            current.vote_count -= 1
            current.save()
            current.against_record.add(user)
    else: 
        current.vote_count += 1
        current.save()
        current.against_record.remove(user)
    return HttpResponseRedirect('/qa/questions/' + offset)

def mark_favourite(request,offset):
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    user = User.objects.get(id = user_id)
    qid = int(offset)
    current = Question.objects.get(id = qid)
    if user not in current.favourite_record.all():
        current.favourite_record.add(user)
    else:
        current.favourite_record.remove(user)
    return HttpResponseRedirect('/qa/questions/' + offset)
    
# add by liuguojun
# display tag related question

def tag_related_question(request, tag_name):
    tag = QATag.objects.filter(name = tag_name)
    str = "Questions Tagged With %s" % (tag_name)
    if len(tag) == 0:
        return render_to_response("zhima.html",{"head":str,'T':'T'})
    tag = QATag.objects.get(name = tag_name)    
    question = tag.question_set.order_by('-question_datetime')
    if len(question) == 0:
        return render_to_response("zhima.html",{"head":str,'T':'T'})
    RepresentNum = 10
    CurrentNum = 1
    if 'page' in request.GET:
        CurrentNum = int(request.GET['page'])     
    QuestionNum = len(question)    
    PageTotalNum = QuestionNum/RepresentNum
    if PageTotalNum * RepresentNum < QuestionNum:
        PageTotalNum += 1
    if CurrentNum > PageTotalNum:
        return HttpResponseRedirect('/qa/tags/NotFound')
    else:
        q = question[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
        PageList = make_list(CurrentNum,PageTotalNum) 
    return render_to_response("zhima.html", {"question_list":q, "head":str,'T':'T','PageTotalNum':PageTotalNum,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList,'Tag':tag})

 

def vote_ajax(request):
    user_id = request.session.get('user_id')
    if not user_id:
        return HttpResponseRedirect('/login/')
    user = User.objects.get(id = user_id)
    message = ['','','']
    qid = int(request.POST['id'])
    if request.POST['type'] == 'question vote up':
        current = Question.objects.get(id = qid)
        message[2] = str(qid)
        if user not in current.pro_record.all():
            if user not in current.against_record.all():
                current.vote_count += 1
                current.save()
                current.pro_record.add(user)
                message[0] = 'on'
                message[1] = str(current.vote_count) 
        else:
            current.vote_count -= 1
            current.save()
            current.pro_record.remove(user)
            message[0] = 'off'
            message[1] = str(current.vote_count)
        return HttpResponse(message[0]+' '+message[1]+' '+message[2])
    elif request.POST['type'] == 'question vote down':
        current = Question.objects.get(id = qid)
        message[2] = str(qid)
        if user not in current.against_record.all():
            if user not in current.pro_record.all():
                current.vote_count -= 1
                current.save()
                current.against_record.add(user)
                message[0] = 'on'
                message[1] = str(current.vote_count) 
        else:
            current.vote_count += 1
            current.save()
            current.against_record.remove(user)
            message[0] = 'off'
            message[1] = str(current.vote_count)
        return HttpResponse(message[0]+' '+message[1]+' '+message[2])
    elif request.POST['type'] == 'mark favourite':
        current = Question.objects.get(id = qid)
        if user not in current.favourite_record.all():
            message[0] = 'on'
            current.favourite_record.add(user)
        else:
            current.favourite_record.remove(user)
            message[0] = 'off'
        return HttpResponse(message[0])
    elif request.POST['type'] == 'answer vote up':
        current = Answer.objects.get(id = qid)
        message[2] = str(qid)
        if user not in current.pro_record.all():
            if user not in current.against_record.all():
                current.vote_count += 1
                current.save()
                current.pro_record.add(user)
                message[0] = 'on'
                message[1] = str(current.vote_count) 
        else:
            current.vote_count -= 1
            current.save()
            current.pro_record.remove(user)
            message[0] = 'off'
            message[1] = str(current.vote_count)
        return HttpResponse(message[0]+' '+message[1]+' '+message[2])
    elif request.POST['type'] == 'answer vote down':
        current = Answer.objects.get(id = qid)
        message[2] = str(qid)
        if user not in current.against_record.all():
            if user not in current.pro_record.all():
                current.vote_count -= 1
                current.save()
                current.against_record.add(user)
                message[0] = 'on'
                message[1] = str(current.vote_count) 
        else:
            current.vote_count += 1
            current.save()
            current.against_record.remove(user)
            message[0] = 'off'
            message[1] = str(current.vote_count)
        return HttpResponse(message[0]+' '+message[1]+' '+message[2])

# Author: wang chenguang

def search(request):
    query = request.GET.get('q','')
    queryvalue = request.GET.get('t','')
    querysort = request.GET.get('sort','')
    if query:
        if queryvalue == 'question':
            qset = (Q(title__icontains=query) | Q(description__icontains=query))
            results = []
            if querysort == 'effective' or querysort == '':
               results = Question.objects.filter(qset).distinct()
               content = 'effective'
            if querysort == 'newest_question':
               results = Question.objects.filter(qset).distinct().order_by('-question_datetime')
               content = 'newest_question'
            if querysort == 'hot_question':
               results = Question.objects.filter(qset).distinct().order_by('-view_count')
               content = 'hot_question'
            if querysort == 'mostvoted':
               results = Question.objects.filter(qset).distinct().order_by('-vote_count')
               content = 'mostvoted'
            #print results
            resultscount = Question.objects.filter(qset).count()
            aset = (
                Q(question__title__icontains=query) |
                Q(question__description__icontains=query)
            )
            answers = Answer.objects.filter(aset)
            answerscount = Answer.objects.filter(aset).count()
            lastanswerlist = []
            for question in results:
               if question.answered_count == 0:   
                  lastanswer = ''
               else:
                  lastanswer = question.answer_set.all().latest('answer_datetime')
               lastanswerlist.append(lastanswer)
               
            qapairs = {}
            i = 0
            for question in results:
               qapairs[question] = lastanswerlist[i]
               i = i + 1
            qalists = []
            qalists.append(qapairs)

            tags = []
            tagscount = []
            for question in results:
               for tag in question.tags.all():
                  #print tag
                  flag = 1
                  for tage in tags:
                     if tage == tag:
                        flag = 0
                  if flag == 1:
                     tags.append(tag)

            for tag in tags:
               #print tag
               count = 0
               for question in results:
                  for tag1 in question.tags.all():
                     #print tag1
                     if tag1 == tag:
                        count = count + 1
               tagscount.append(count)
            #print tags
            CurrentNum = 1
            #print CurrentNum
            RepresentNum = 10
            QuestionNum = int(resultscount)#
            PageTotalNum = QuestionNum/RepresentNum
            if PageTotalNum * RepresentNum < QuestionNum:
                PageTotalNum += 1
            if CurrentNum > PageTotalNum:
                return HttpResponseRedirect('/qa/search/pages')
            else:
                results = results[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]#
                #tag_list = QATag.objects.order_by('-count')[0:10]
                i = CurrentNum
                PageList = []
                if PageTotalNum == 1:
                    PageList = []
                elif PageTotalNum <= 10:
                    i = 1
                    while i <= PageTotalNum:
                        PageList.append(i)
                        i = i + 1
                elif CurrentNum <= 5:
                    i = 1
                    while i <= 10:
                        PageList.append(i)
                        i = i + 1
                elif CurrentNum >= PageTotalNum - 5:
                    i = PageTotalNum - 9
                    while i <= PageTotalNum:
                        PageList.append(i)
                        i = i + 1
                else:
                    i = CurrenTNum - 5
                    while i < CurrentNum + 5:
                        PageList.append(i)
                        i = i + 1
                return render_to_response("search.html", {
                    #"question_list":q,
                    "results": results,
                    "query": query,
                    #"querysort":querysort,
                    "resultscount": resultscount,
                    "answers": answers,
                    "answerscount": answerscount,
                    "lastanswerlist": lastanswerlist,
                    "tags": tags,
                    "tagscount": tagscount,
                    #"head":"All Questions",
                    #"tag_list":tag_list,
                    'PageTotalNum':PageTotalNum,
                    'CurrentNum':CurrentNum,
                    'LastNum':CurrentNum-1,
                    'NextNum':CurrentNum+1,
                    'PageList':PageList,
                    'content':content,
                })
        if queryvalue == 'tag':
            qset = (
                Q(name__icontains=query)
            )
            tagscount = []
            tags = QATag.objects.filter(qset).distinct().order_by('count')
            if querysort == '' or querysort == 'used':
               tags = QATag.objects.filter(qset).distinct().order_by('count')
               content = 'used'
            if querysort == 'name':
               tags = QATag.objects.filter(qset).distinct().order_by('name')
               content = 'name'
            for tag in tags:
               #print tag
               count = 0
               for question in Question.objects.all():
                  for tag1 in question.tags.all():
                     #print tag1
                     if tag1 == tag:
                        count = count + 1
               tagscount.append(count)
            return render_to_response("tags.html", {
                 "tags": tags,
                 "query": query,
                 "tagscount": tagscount,
                 'content':content,
                 'Tags':'Tags',
            })
        if queryvalue == 'user':
            qset = (
                Q(name__icontains=query)
            )
            users = User.objects.filter(qset).distinct()
            if querysort == '' or querysort == 'score':
               users = User.objects.filter(qset).distinct()
               content = 'score'
            if querysort == 'newest_enter':
               users = User.objects.filter(qset).distinct().order_by('-register_datetime')
               content = 'newest_enter'
            if querysort == 'last_enter':
               users = User.objects.filter(qset).distinct().order_by('register_datetime')
               content = 'last_enter'
            if querysort == 'user_name':
               users = User.objects.filter(qset).distinct().order_by('name')
               content = 'user_name'
            userscount = User.objects.filter(qset).count()
            return render_to_response("users.html", {
                 "users": users,
                 "query": query,
                 "userscount": userscount,
                 'content':content,
                 'Users':'users'
            })
    else:
        results = []
        resultscount = '0'
        answers = []
        answerscount = '0'
        lastanswerlist = []
        tags = []
        tagscount = []
        PageTotalNum = 0
        CurrentNum = 0
        LastNum = 0
        NextNum = 0
        PageList = []
        content = 'effective'
        return HttpResponseRedirect('/qa/questions/')
        

def search_by_page(request,offset):
    query = request.GET.get('q','')
    queryvalue = request.GET.get('t','')
    querysort = request.GET.get('sort','')

    if query:
        if queryvalue == 'question':
            qset = (Q(title__icontains=query) | Q(description__icontains=query))
            results = []
            if querysort == 'effective' or querysort == '':
               results = Question.objects.filter(qset).distinct()
               content = 'effective'
            if querysort == 'newest_question':
               results = Question.objects.filter(qset).distinct().order_by('-question_datetime')
               content = 'newest_question'
            if querysort == 'hot_question':
               results = Question.objects.filter(qset).distinct().order_by('-view_count')
               content = 'hot_question'
            if querysort == 'mostvoted':
               results = Question.objects.filter(qset).distinct().order_by('-vote_count')
               content = 'mostvoted'
            resultscount = Question.objects.filter(qset).count()
            aset = (
                Q(question__title__icontains=query) |
                Q(question__description__icontains=query)
            )
            answers = Answer.objects.filter(aset)
            answerscount = Answer.objects.filter(aset).count()
            lastanswerlist = []
            for question in results:
               if question.answered_count == 0:   
                  lastanswer = ''
               else:
                  lastanswer = question.answer_set.all().latest('answer_datetime')
               lastanswerlist.append(lastanswer)
            tags = []
            tagscount = []
            for question in results:
               for tag in question.tags.all():
                  print tag
                  flag = 1
                  for tage in tags:
                     if tage == tag:
                        flag = 0
                  if flag == 1:
                     tags.append(tag)

            for tag in tags:
               count = 0
               for question in results:
                  for tag1 in question.tags.all():
                     if tag1 == tag:
                        count = count + 1
               tagscount.append(count)
            CurrentNum = int(offset)
            #print CurrentNum
            RepresentNum = 10
            QuestionNum = int(resultscount)#
            PageTotalNum = QuestionNum/RepresentNum
            if PageTotalNum * RepresentNum < QuestionNum:
                PageTotalNum += 1
            if CurrentNum > PageTotalNum:
                return HttpResponseRedirect('/qa/search/pages')
            else:
                results = results[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]#
                #tag_list = QATag.objects.order_by('-count')[0:10]
                i = CurrentNum
                PageList = []
                if PageTotalNum == 1:
                    PageList = []
                elif PageTotalNum <= 10:
                    i = 1
                    while i <= PageTotalNum:
                        PageList.append(i)
                        i = i + 1
                elif CurrentNum <= 5:
                    i = 1
                    while i <= 10:
                        PageList.append(i)
                        i = i + 1
                elif CurrentNum >= PageTotalNum - 5:
                    i = PageTotalNum - 9
                    while i <= PageTotalNum:
                        PageList.append(i)
                        i = i + 1
                else:
                    i = CurrentNum - 5
                    while i < CurrentNum + 5:
                        PageList.append(i)
                        i = i + 1
                return render_to_response("search.html", {
                    #"question_list":q,
                    "results": results,
                    "query": query,
                    #"querysort":querysort,
                    "resultscount": resultscount,
                    "answers": answers,
                    "answerscount": answerscount,
                    "lastanswerlist": lastanswerlist,
                    "tags": tags,
                    "tagscount": tagscount,
                    #"head":"All Questions",
                    #"tag_list":tag_list,
                    'PageTotalNum':PageTotalNum,
                    'CurrentNum':CurrentNum,
                    'LastNum':CurrentNum-1,
                    'NextNum':CurrentNum+1,
                    'PageList':PageList,
                    'content':content,
                })
    else:
        results = []
        resultscount = '0'
        answers = []
        answerscount = '0'
        lastanswerlist = []
        tags = []
        tagscount = []
        PageTotalNum = 0
        CurrentNum = 0
        LastNum = 0
        NextNum = 0
        PageList = []
        return HttpResponseRedirect('/qa/questions/') 
    



def markdown_help(request):
    return render_to_response('markdown_help.html')
   
def faq(request):
    return render_to_response('qa_faq.html')

def contact(request):
    return render_to_response('qa_contact.html')

def showQuestion_by_page(request,offset):
    CurrentNum = int(offset)
    RepresentNum = 10
    QuestionNum = len(Question.objects.all())
    PageTotalNum = QuestionNum/RepresentNum
    if PageTotalNum * RepresentNum < QuestionNum:
        PageTotalNum += 1
    if CurrentNum > PageTotalNum:
        return HttpResponseRedirect('/qa/questions/page')
    else:
        q = Question.objects.all()[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
        tag_list = QATag.objects.order_by('-count')[0:10]
        PageList = make_list(CurrentNum,PageTotalNum)
        return render_to_response("zhima.html", {"question_list":q, "head":"All Questions", "tag_list":tag_list,'PageTotalNum':PageTotalNum,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList})

# add by liuguojun
# for sphinx full txt search
def quicksearch(request):
    
    query = request.GET.get('q','')
    queryvalue = request.GET.get('t','')
    querysort = request.GET.get('sort','')

    print "Query is:", query
    if query:
        mode = SPH_MATCH_ALL
        host = 'localhost'
        port = 9312
        index = '*'
        filtercol = 'group_id'
        sortby = ''
        limit = 0

        cl = SphinxClient()
        cl.SetServer( host, port )
        cl.SetWeights( [100, 1] )
        cl.SetMatchMode( mode )

        #cl.SetSortMode( SPH_SORT_EXTENDED, sortby )
        
        res = cl.Query ( query, index )
        
        if not res:
            print 'query failed: %s' % cl.GetLastError()
            sys.exit(1)
 
        if cl.GetLastWarning():
            print 'WARNING: %s\n' % cl.GetLastWarning()

        id_list = []
        if res.has_key('matches'):
            for match in res['matches']:
                id_list.append(match['id'])

        result = []
        print "len of id_list is:%d" % len(id_list)
        if id_list:
            for qid in id_list:
                result.append(Question.objects.get(id=qid))
        print result
        return render_to_response("quicksearch.html", {
                "query":query,
                "results": result,
                  }) 
# add by sdk
# show all the tags
def showTag_by_page(request,offset):
    CurrentNum = int(offset)
    RepresentNum = 28  
    TagNum = len(QATag.objects.all())
    PageTotalNum = TagNum/RepresentNum
    if PageTotalNum * RepresentNum < TagNum:
        PageTotalNum += 1
    if CurrentNum > PageTotalNum:
        return HttpResponseRedirect('/qa/questions/tags/page')
    else:
        if 'sort' in request.GET and request.GET['sort'] == 'name':
            tag_all_list = QATag.objects.order_by('name')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
            content = 'name'
        else:
            tag_all_list = QATag.objects.order_by('-count')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
            content = 'count'
        PageList = make_list(CurrentNum,PageTotalNum)
    return render_to_response('showTag.html',{"tag_all_list":tag_all_list,'PageTotalNum':PageTotalNum,'content':content,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList})

def showTag(request):
    RepresentNum = 28
    TagNum = len(QATag.objects.all())
    PageTotalNum = TagNum/RepresentNum
    if PageTotalNum * RepresentNum < TagNum:
        PageTotalNum += 1
    CurrentNum = 1
    if 'sort' in request.GET and request.GET['sort'] == 'name':
        tag_all_list = QATag.objects.order_by('name')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
        content = 'name'
    else:
        tag_all_list = QATag.objects.order_by('-count')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
        content = 'count'
    i = CurrentNum
    PageList = []
    if PageTotalNum == 1:
        PageList = []
    else:
        while i < CurrentNum + 10:
            PageList.append(i)
            if i >= PageTotalNum:
                break
            i = i + 1
    return render_to_response('showTag.html',{"tag_all_list":tag_all_list,'PageTotalNum':PageTotalNum,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList,'content':content})


def showQaUser(request):
    RepresentNum = 35
    UserNum = len(User.objects.all())
    PageTotalNum = UserNum/RepresentNum
    if PageTotalNum * RepresentNum < UserNum:
        PageTotalNum += 1
    CurrentNum = 1
    if 'sort' in request.GET:
        if request.GET['sort'] == 'jointime':
            user_list = User.objects.order_by('-register_datetime')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
            content = 'jointime'
        else:
            user_list = User.objects.order_by('name')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
            content = 'name'
    else:
        user_list = User.objects.order_by('-register_datetime')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
        content = 'jointime'
    i = CurrentNum
    PageList = []
    if PageTotalNum == 1:
        PageList = []
    else:
        while i < CurrentNum + 10:
            PageList.append(i)
            if i >= PageTotalNum:
                break
            i = i + 1
    return render_to_response('showQaUser.html',{"user_list":user_list,'PageTotalNum':PageTotalNum,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList,'content':content})

def showQaUser_by_page(request,offset):
    CurrentNum = int(offset)
    RepresentNum = 35
    UserNum = len(User.objects.all())
    PageTotalNum = UserNum/RepresentNum
    if PageTotalNum * RepresentNum < UserNum:
        PageTotalNum += 1
    if CurrentNum > PageTotalNum:
        return HttpResponseRedirect('/qa/questions/tags/page')
    else:
        if 'sort' in request.GET:
            if request.GET['sort'] == 'jointime':
                user_list = User.objects.order_by('-register_datetime')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
                content = 'jointime'
            else:
                 user_list = User.objects.order_by('name')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
                 content = 'name'
        else:
            user_list = User.objects.order_by('-register_datetime')[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
            content = 'jointime'
        PageList = make_list(CurrentNum,PageTotalNum)
    return render_to_response('showQaUser.html',{"user_list":user_list,'PageTotalNum':PageTotalNum,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList,'content':content})

def Unanswered(request):
    RepresentNum = 10
    Unanswered = []
    Questions = Question.objects.order_by('-question_datetime')
    for question in Questions:
        if len(question.answer_set.all()) == 0:
            Unanswered.append(question)
    QuestionNum = len(Unanswered)
    PageTotalNum = QuestionNum/RepresentNum
    if PageTotalNum * RepresentNum < QuestionNum:
        PageTotalNum += 1
    q = Unanswered[:RepresentNum]
    tag_list = QATag.objects.order_by('-count')[0:10]
    CurrentNum = 1
    i = CurrentNum
    PageList = []
    if PageTotalNum == 1:
        PageList = []
    else:
        while i < CurrentNum + 10:
            PageList.append(i)
            if i >= PageTotalNum:
                break
            i = i + 1
    return render_to_response("zhima.html", {"question_list":q, "head":"All unanswered Questions", "tag_list":tag_list,'PageTotalNum':PageTotalNum,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList,'unanswered':'unanwered'})

def UnansweredPage(request,offset):
    CurrentNum = int(offset)
    RepresentNum = 10
    Unanswered = []
    Questions = Question.objects.order_by('-question_datetime')
    for question in Questions:
        if len(question.answer_set.all()) == 0:
            Unanswered.append(question)
    QuestionNum = len(Unanswered)
    PageTotalNum = QuestionNum/RepresentNum
    if PageTotalNum * RepresentNum < QuestionNum:
        PageTotalNum += 1
    q = Unanswered[:RepresentNum]
    tag_list = QATag.objects.order_by('-count')[0:10]
    if CurrentNum > PageTotalNum:
        return HttpResponseRedirect('/qa/questions/page')
    else:
        q = Question.objects.all()[RepresentNum * (CurrentNum - 1):RepresentNum * CurrentNum]
        tag_list = QATag.objects.order_by('-count')[0:10]
        PageList = make_list(CurrentNum,PageTotalNum)
    return render_to_response("zhima.html", {"question_list":q, "head":"All unanswered Questions", "tag_list":tag_list,'PageTotalNum':PageTotalNum,'CurrentNum':CurrentNum,'LastNum':CurrentNum-1,'NextNum':CurrentNum+1,'PageList':PageList,'unanswered':'unanwered'})

def qa_userpage(request,offset):
    user_id = int(offset)
    user = User.objects.filter(id = user_id)
    if len(user) == 0:
        return HttpResponseRedirect('/qa/questions/users/NotFound')
    user = User.objects.get(id = user_id)
    question = user.questions.order_by('-question_datetime')
    answer = user.answer_set.order_by('-answer_datetime')
    tag = user.qatag_set.order_by('-count')
    question_list = question
    answer_list = answer
    tag_list = tag
    vote_count = []
    vote_count.append(len(user.pro_question.all())+len(user.pro_answer.all()))
    vote_count.append(len(user.against_question.all())+len(user.against_anwer.all()))
    vote_count.append(vote_count[0] +vote_count[1])
    return render_to_response('qa_userpage.html',{'user':user,'question_list':question_list,'tag_list':tag_list,'answer_list':answer_list,'vote_count':vote_count})
